package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a04_组合总和复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/2/10
 */
public class a04_组合总和3复习2 {
    public static void main(String[] args) {
        List<List<Integer>> lists = combinationSum3(3, 7);
    }

    public static List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        traversal(result, path,0,k,n,1);
        return result;
    }

    private static void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int sum,
                           int targetNum,
                           int targetSum,
                           int startIdx){
        if(path.size() == targetNum){
            if(sum == targetSum){
                result.add(new ArrayList<>(path));
                return;
            }else {
                return;
            }
        }

        for (int i = startIdx; i <= 9; i++) {
            path.add(i);
            sum = sum + i;
            traversal(result, path,sum, targetNum, targetSum, i + 1);
            path.removeLast();
            sum = sum - i;
        }
    }
}
